<?php
namespace app\admin\controller;
use app\common\controller\Adminbase;
use \think\Loader;
use \think\Db;
use \think\Request;

// +----------------------------------------------------------------------
// | XpCms
// +----------------------------------------------------------------------
// | Copyright (c) 2021-2099
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Mercurio（Xp） <725668993@qq.com>
// +----------------------------------------------------------------------

/*
** 内容模型 控制器
*/

class Model extends Adminbase {
	private static $_model = null; // 数据表对象
	
	// 优先加载
	public function _initialize() {
		parent::_initialize();
		
		// 实例化数据表模型
		self::$_model = Loader::model('model');
		
	}
	
	// 分类列表
	public function index() {
		
		$lists = self::$_model -> modelLists();
		
		$this -> assign('modellists', $lists);
		return view('index');
	}
	
	// 新增分类页面
	public function add() {
		return view('add');
	}
	
	// 保存新增分类
	public function addsave() {
		
		$inputs = input('post.');
		//获取数据库所有表名
        $tables = Db::getConnection()->getTables();
        //获取表前缀
        $prefix = config('database.prefix');
        //拼接表名
        $tablename = $prefix.$inputs['tablename'];
        //判断表名是否存在
        if(in_array($tablename, $tables)){
            $this->error('该表已经存在！请更换数据表名称');
        }
        //首字母转大写
        $name = ucfirst($inputs['tablename']);
        $defaulttable = $inputs['defaulttable'];//获取默认表
        unset($inputs['defaulttable']);
        // 验证新增数据 name 是否重复
		$this -> checkNameAdd($inputs);
		$inputs['mcode'] = get_auto_code(self::$_model -> getLastCode());
		// 保存数据
		$moduleid = Db::name('model')->insertGetId($inputs);
		if(empty($moduleid)){
			$this -> success('添加模型失败！');
		}
		if($defaulttable == '1'){   // 默认文章表
		    Db::execute("CREATE TABLE `".$tablename."` (
			  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
			  `cid` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '栏目ID',
			  `title` varchar(120) NOT NULL DEFAULT '' COMMENT '标题',
			  `content` text NOT NULL DEFAULT '' COMMENT '文章内容',
			  `time_create` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
			  `time_report` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '发布时间',
			  `time_update` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '更新时间',
			  `status` tinyint(2) unsigned NOT NULL DEFAULT '0' COMMENT '默认0待审核1已审核-1已删除',
			  `filename` varchar(40) NOT NULL COMMENT '自定义文件名',
			  `click` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '浏览数',
			  `template` varchar(40) NOT NULL DEFAULT '' COMMENT '模型模板',
			  `seo_title` varchar(300) NOT NULL DEFAULT '' COMMENT 'seo标题',
			  `seo_keys` varchar(150) NOT NULL DEFAULT '' COMMENT 'seo关键词',
			  `seo_desc` mediumtext NOT NULL DEFAULT '' COMMENT 'seo描述',
			  PRIMARY KEY (`id`)
			) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8");
			Db::execute("INSERT INTO `".$prefix."field` (`moduleid`,`field`,`name`,`isrequire`,`minlength`,`maxlength`,`type`,`setup`,`sort`,`status`,`issystem`) VALUES ( '".$moduleid."', 'cid', '栏目', '1', '1', '10', 'cid', '','1','1', '1')");
			Db::execute("INSERT INTO `".$prefix."field` (`moduleid`,`field`,`name`,`isrequire`,`minlength`,`maxlength`,`type`,`setup`,`sort`,`status`,`issystem`) VALUES ( '".$moduleid."', 'title', '标题', '1', '1', '120', 'text', '','2','1', '1')");
			Db::execute("INSERT INTO `".$prefix."field` (`moduleid`,`field`,`name`,`isrequire`,`minlength`,`maxlength`,`type`,`setup`,`sort`,`status`,`issystem`) VALUES ( '".$moduleid."', 'content', '内容', '1', '0', '0', 'editor', 'array (\n  \'edittype\' => \'UEditor\',\n)','3', '1', '1')");
			Db::execute("INSERT INTO `".$prefix."field` (`moduleid`,`field`,`name`,`isrequire`,`minlength`,`maxlength`,`type`,`setup`,`sort`,`status`,`issystem`) VALUES ( '".$moduleid."', 'status', '状态', '1', '0', '0', 'radio', 'array (\n  \'options\' => \'已审核|1\r\n待审核|0\',\n  \'fieldtype\' => \'tinyint\',\n  \'numbertype\' => \'1\',\n  \'labelwidth\' => \'75\',\n  \'default\' => \'1\',\n)','4','1', '1')");
			Db::execute("INSERT INTO `".$prefix."field` (`moduleid`,`field`,`name`,`isrequire`,`minlength`,`maxlength`,`type`,`setup`,`sort`,`status`,`issystem`) VALUES ( '".$moduleid."', 'filename', '自定义文件名', '0', '0', '10', 'text', '','5','1', '1')");
			Db::execute("INSERT INTO `".$prefix."field` (`moduleid`,`field`,`name`,`isrequire`,`minlength`,`maxlength`,`type`,`setup`,`sort`,`status`,`issystem`) VALUES ( '".$moduleid."', 'time_create', '创建时间', '1', '0', '0', 'date', '','6','1', '1')");
			Db::execute("INSERT INTO `".$prefix."field` (`moduleid`,`field`,`name`,`isrequire`,`minlength`,`maxlength`,`type`,`setup`,`sort`,`status`,`issystem`) VALUES ( '".$moduleid."', 'time_report', '发布时间', '1', '0', '0', 'date', '','7','1', '1')");
			Db::execute("INSERT INTO `".$prefix."field` (`moduleid`,`field`,`name`,`isrequire`,`minlength`,`maxlength`,`type`,`setup`,`sort`,`status`,`issystem`) VALUES ( '".$moduleid."', 'time_update', '更新时间', '1', '0', '0', 'date', '','8','1', '1')");
			Db::execute("INSERT INTO `".$prefix."field` (`moduleid`,`field`,`name`,`isrequire`,`minlength`,`maxlength`,`type`,`setup`,`sort`,`status`,`issystem`) VALUES ( '".$moduleid."', 'click', '浏览数', '0', '0', '0', 'text', '','10','1', '1')");
			Db::execute("INSERT INTO `".$prefix."field` (`moduleid`,`field`,`name`,`isrequire`,`minlength`,`maxlength`,`type`,`setup`,`sort`,`status`,`issystem`) VALUES ( '".$moduleid."', 'template', '模型模板', '0', '0', '0', 'template', '','9', '1', '1')");
			Db::execute("INSERT INTO `".$prefix."field` (`moduleid`,`field`,`name`,`isrequire`,`minlength`,`maxlength`,`type`,`setup`,`sort`,`status`,`issystem`) VALUES ( '".$moduleid."', 'seo_title', 'seo标题', '0', '1', '300', 'text', '','10', '1', '1')");
			Db::execute("INSERT INTO `".$prefix."field` (`moduleid`,`field`,`name`,`isrequire`,`minlength`,`maxlength`,`type`,`setup`,`sort`,`status`,`issystem`) VALUES ( '".$moduleid."', 'seo_keys', 'seo关键词', '0', '1', '150', 'text', '','11', '1', '1')");
			Db::execute("INSERT INTO `".$prefix."field` (`moduleid`,`field`,`name`,`isrequire`,`minlength`,`maxlength`,`type`,`setup`,`sort`,`status`,`issystem`) VALUES ( '".$moduleid."', 'seo_desc', 'seo描述', '0', '0', '0', 'text', '','12', '1', '1')");
		}
		
		if ($moduleid  !==false) {
            $this->success('添加模型成功', 'index');
        }else{
            $this->error('添加模型失败');
        }
	}
	
	// 编辑分类页面
	public function edit() {
		
		$id = input('param.id/d');
		if(!$id){
			$this -> error('参数错误');
		}
		
		$lists = self::$_model -> getModelDetail($id);
		if(!$lists){
			$this -> error('参数错误');
		}
		
		$this -> assign('lists', $lists);
		return view('add');
	}
	
	//模型删除
    public function del(){
        if(request()->isPost()) {
            $id = input('post.id');
            if( empty($id) ){
                return ['error'=>1,'msg'=>'ID不存在'];
            }
            Db::name('model')
                ->where('id','=',$id)
                ->delete();
            return ['error'=>0,'msg'=>'删除成功!'];
        }
    }
	
	// 保存编辑分类
	public function editsave() {
		
		$inputs = input('post.');
		
		$id = (int) $inputs['id'];
		if(!$id){
			$this -> error('参数错误');
		}
		
// 		// 使用模型验证器进行验证
// 		$result = $this -> validate($inputs, 'Friendlink.edit');
// 		if(true !== $result){
// 			// 验证失败 输出错误信息
// 			$this -> error($result);
// 		}
		
		$find = self::$_model -> where(array('id' => $id)) -> value('id');
		if(!$find){
			$this -> error('参数错误');
		}
		
		// 验证更新数据 name 是否重复
		$this -> checkNameUpdate($inputs);
		unset($inputs['id']);
		
		// 保存数据
		if(self::$_model -> save($inputs, array('id' => $id))){
			$this -> success('操作成功');
		}
		
		$this -> error('操作失败或没有数据可更新');
	}
	
	// 编辑模型状态
	public function editstatus() {
		
		$id = input('post.id/d');
		if(!$id){
			$this -> error('参数错误');
		}
		
		$result = self::$_model -> editStatus($id);
		if($result){
			$this -> success('操作成功');
		}
		$this -> error('操作失败');
	}
	
	
	// 删除分类
	public function deletes() {
		
		$id = input('post.id/d');
		if(!$id){
			$this -> error('参数错误');
		}
		
		$result = self::$_model -> deletes($id);
		if($result['status'] == 1){
			$this -> success('删除成功');
		}
		$this -> error($result['msg']);
	}
	
	public function field(){

        $nodostatus = array('cid','title','content','status','time_create');
        $sysfield = array('cid','title','thumb','keywords','description','status','create_time','url','template');

        $list = Db::name('field')
            ->where("moduleid",'=',input('id'))
            ->order('sort asc,id asc')
            ->select();
        foreach ($list as $k=>$v){
            if($v['status']==1){
                if(in_array($v['field'],$nodostatus)){
                    $list[$k]['disable']=2;//状态不可变更
                }else{
                    $list[$k]['disable']=0;//已启用
                }
            }else{
                $list[$k]['disable']=1;//已禁用
            }

            if(in_array($v['field'],$sysfield)){
                $list[$k]['delStatus']=1;//不可删除
            }else{
                $list[$k]['delStatus']=0;//可删除
            }
        }
        $this->view->assign('list'     , $list);
        $this->view->assign('moduleid' , input('id'));
        return $this->view->fetch();
    }
    
    //添加字段
    public function fieldAdd(){
        $this->view->assign('moduleid',input('moduleid'));
        $this->view->assign('info',null);
        $this->view->assign('fieldInfo',null);
        return $this->view->fetch();
    }
    
    //添加字段保存
    public function fieldAddPost(){
        if(request()->isPost()){
            if(input('isajax')) {
                //调用字段设置模版
                $this->assign(input('get.'));
                $this->assign(input('post.'));
                //根据name取值
                if(input('name')){
                    $fieldInfo = Db::name('field')
                        ->where('moduleid','=',input('moduleid'))
                        ->where('field','=',input('name'))
                        ->find();
                    $fieldInfo['setup'] = string2array($fieldInfo['setup']);
                    $this->view->assign('fieldInfo',$fieldInfo);
                }else{
                    $this->view->assign('fieldInfo',null);
                }
                return $this->view->fetch('fieldAddType');
            }else{
                $data = input('post.');
                $fieldName=$data['field'];
                $prefix=config('database.prefix');
                $name = Db::name('model')
                    ->where('id','=',$data['moduleid'])
                    ->value('tablename');
                $tablename=$prefix.$name;
                $Fields=Db::getTableFields($tablename);
                if(in_array($fieldName,$Fields)){
                    $this->error('字段名已经存在！');
                }
                $addfieldsql =$this->get_tablesql($data,'add');
                if(isset($data['setup'])) {
                    $data['setup'] = array2string($data['setup']);
                }
                $data['status'] =1;
                $model = Db::name('field');
                if ($model->insert($data) !==false) {
                    if(is_array($addfieldsql)){
                        foreach($addfieldsql as $sql){
                            $model->execute($sql);
                        }
                    }else{
                        $model->execute($addfieldsql);
                    }
                    $this->success('添加成功！', url('field',array('id'=>input('post.moduleid'))));
                } else {
                    $this->error('添加失败！');
                }
            }
        }
    }
    
    //编辑字段
    public function fieldEdit(){
        $model = Db::name('field');
        $id = input('id');
        if(empty($id)){
            $this->error('缺少必要的参数！');
        }
        $fieldInfo = $model
            ->where('id','=',$id)
            ->find();
        if($fieldInfo['setup']) $fieldInfo['setup']=string2array($fieldInfo['setup']);
        $this->view->assign('info',$fieldInfo);
        $this->view->assign('moduleid', input('moduleid'));
        return $this->view->fetch('fieldadd');
    }
    
    //编辑字段保存
    public function fieldEditPost(){
        if(request()->isPost()){
            $data = Request::instance()->except('oldfield');
            $oldfield = input('oldfield');
            $fieldName = $data['field'];
            $name = Db::name('model')
                ->where('id' , '=' ,$data['moduleid'])
                ->value('tablename');
            $prefix=config('database.prefix');
            if($this->_iset_field($prefix.$name,$fieldName) && $oldfield!=$fieldName){
                $this->error('字段名重复！');
            }
            $editfieldsql =$this->get_tablesql(input(),'edit');

            if(array_key_exists ("setup",$data)&&$data['setup']){
                $data['setup']=array2string($data['setup']);
            }
            $model = Db::name('field');

            if (false !== $model->update($data)) {
                if(is_array($editfieldsql)){
                    foreach($editfieldsql as $sql){
                        $model->execute($sql);
                    }
                }else{
                    $model->execute($editfieldsql);
                }
                $this->success('修改成功！',url('field',array('id'=>input('moduleid'))));
            } else {
                $this->error('修改失败！');
            }
        }
    }
    
    public function get_tablesql($info,$do){
        $comment = $info['name'];
        $fieldtype = $info['type'];

        if(isset($info['setup']['fieldtype'])){
            $fieldtype=$info['setup']['fieldtype'];
        }
        $moduleid = $info['moduleid'];
        $default = '';
        if(isset($info['setup']['default'])){
            $default=$info['setup']['default'];
        }
        $field = $info['field'];
        $prefix = config('database.prefix');
        $name = Db::name('model')
            ->where('id',$moduleid)
            ->value('tablename');
        $tablename=$prefix.$name;
        $maxlength = intval($info['maxlength']);
        $minlength = intval($info['minlength']);
        $numbertype = '';
        if(isset($info['setup']['numbertype'])){
            $numbertype=$info['setup']['numbertype'];
        }
        if($do=='add'){
            $do = ' ADD ';
        }else{
            $oldfield = $info['oldfield'];
            $do =  " CHANGE `".$oldfield."` ";
        }
        switch($fieldtype) {
            case 'varchar':
                if(!$maxlength){$maxlength = 255;}
                $maxlength = min($maxlength, 255);
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( $maxlength ) NOT NULL DEFAULT '$default' COMMENT '$comment'";
                break;
            case 'title':
                if(!$maxlength){$maxlength = 255;}
                $maxlength = min($maxlength, 255);
                $sql[] = "ALTER TABLE `$tablename` $do `$field` VARCHAR( $maxlength ) NOT NULL DEFAULT '$default' COMMENT '$comment'";

                break;
            case 'catid':
                $sql = "ALTER TABLE `$tablename` $do `$field` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0' COMMENT '$comment'";
                break;

            case 'number':
                $decimaldigits = $info['setup']['decimaldigits'];
                $default = $decimaldigits == 0 ? intval($default) : floatval($default);
                $sql = "ALTER TABLE `$tablename` $do `$field` ".($decimaldigits == 0 ? 'INT' : 'decimal( 10,'.$decimaldigits.' )')." ".($numbertype ==1 ? 'UNSIGNED' : '')."  NOT NULL DEFAULT '$default'  COMMENT '$comment'";
                break;

            case 'tinyint':
                if(!$maxlength) $maxlength = 3;
                $maxlength = min($maxlength,3);
                $default = intval($default);
                $sql = "ALTER TABLE `$tablename` $do `$field` TINYINT( $maxlength ) ".($numbertype ==1 ? 'UNSIGNED' : '')." NOT NULL DEFAULT '$default'  COMMENT '$comment'";
                break;


            case 'smallint':
                $default = intval($default);
                $sql = "ALTER TABLE `$tablename` $do `$field` SMALLINT ".($numbertype ==1 ? 'UNSIGNED' : '')." NOT NULL DEFAULT '$default' COMMENT '$comment'";
                break;

            case 'int':
                $default = intval($default);
                $sql = "ALTER TABLE `$tablename` $do `$field` INT ".($numbertype ==1 ? 'UNSIGNED' : '')." NOT NULL DEFAULT '$default' COMMENT '$comment'";
                break;

            case 'mediumint':
                $default = intval($default);
                $sql = "ALTER TABLE `$tablename` $do `$field` INT ".($numbertype ==1 ? 'UNSIGNED' : '')." NOT NULL DEFAULT '$default' COMMENT '$comment'";
                break;

            case 'mediumtext':
                $sql = "ALTER TABLE `$tablename` $do `$field` MEDIUMTEXT NOT NULL COMMENT '$comment'";
                break;

            case 'text':
                $sql = "ALTER TABLE `$tablename` $do `$field` TEXT NOT NULL COMMENT '$comment'";
                break;

            //case 'typeid':
            //$sql = "ALTER TABLE `$tablename` $do `$field` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0'";
            //break;

            case 'datetime':
                $sql = "ALTER TABLE `$tablename` $do `$field` INT(11) UNSIGNED NOT NULL DEFAULT '0' COMMENT '$comment'";
                break;

            case 'editor':
                $sql = "ALTER TABLE `$tablename` $do `$field` TEXT NOT NULL COMMENT '$comment'";
                break;

            case 'image':
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( 255 ) NOT NULL DEFAULT '' COMMENT '$comment'";
                break;

            case 'images':
                $sql = "ALTER TABLE `$tablename` $do `$field` MEDIUMTEXT NOT NULL COMMENT '$comment'";
                break;

            case 'file':
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( 80 ) NOT NULL DEFAULT '' COMMENT '$comment'";
                break;

            case 'files':
                $sql = "ALTER TABLE `$tablename` $do `$field` MEDIUMTEXT NOT NULL COMMENT '$comment'";
                break;
            case 'template':
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( 80 ) NOT NULL DEFAULT '' COMMENT '$comment'";
                break;
            case 'linkage':
                $sql = "ALTER TABLE `$tablename` $do `$field` VARCHAR( 80 ) NOT NULL DEFAULT '' COMMENT '$comment'";
                break;
        }
        return $sql;
    }
    
    //字段状态
    public function fieldState(){
        if(request()->isPost()){
            $id = input('post.id');
            if (empty($id)){
                return ['error'=>1,'msg'=>'ID不存在!'];
            }

            $status = Db::name('field')->where('id','=',$id)->value('status');
            $status = $status==1?0:1;
            if(Db::name('field')->where('id','=',$id)->update(['status'=>$status])!==false){
                return ['error'=>0,'msg'=>'设置成功!'];
            }else{
                return ['error'=>1,'msg'=>'设置失败!'];
            }
        }
    }
    
    //字段排序
    public function fieldSort(){
        $data = input();
        if(Db::name('field')->update($data)!==false){
            return $result = ['error' => 0,'msg' => '操作成功！'];
        }else{
            return $result = ['error'=>1,'msg'=>'操作失败！'];
        }
    }
    
    //删除字段
    public function fieldDel() {
        $id=input('id');
        $r = Db::name('field')->find($id);
        Db::name('field')->delete($id);

        $moduleid = $r['moduleid'];

        $field = $r['field'];

        $prefix=config('database.prefix');
        $name = Db::name('model')->where('mcode','=',$moduleid)->value('tablename');
        $tablename=$prefix.$name;

        Db::name('field')->execute("ALTER TABLE `$tablename` DROP `$field`");

        return ['error'=>0,'msg'=>'删除成功！'];
    }
    
    protected function _iset_field($table,$field){
        $fields = Db::getTableFields($table);
        return array_search($field,$fields);
    }
	
	// 验证新增数据 name 是否重复添加
	private function checkNameAdd($data) {
		$checkData = array('name' => $data['name']);
		$find = self::$_model -> where($checkData) -> find();
		if($find){
			$this -> error('同样的记录已经存在');
		}
		return true;
	}
	
	// 验证更新数据 name 是否重复添加
	private function checkNameUpdate($data) {
		
		$checkData = array('name' => $data['name']);
		$find = self::$_model -> where($checkData) -> value('id');
		
		if($find && $find != $data['id']){
			$this -> error('同样的记录已经存在');
		}
		return true;
	}
	
}
